package com.example.cash.craft.controller;

import com.example.cash.craft.exception.RequestParameterNotValidException;
import com.example.cash.craft.pojo.core.CurrentPrincipal;
import com.example.cash.craft.pojo.param.OrderAddNewParam;
import com.example.cash.craft.pojo.vo.OrderFullInfoVO;
import com.example.cash.craft.pojo.vo.OrderSimpleInfoVO;
import com.example.cash.craft.pojo.vo.PageData;
import com.example.cash.craft.service.IOrderService;
import com.example.cash.craft.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@Tag(name = "5. 订单管理模块")
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Operation(summary = "[用户] 新增订单")
    @ApiOperationSupport(order = 100)
    @PostMapping("/add-new")
    public JsonResult<Void> addNew(@ParameterObject @Valid OrderAddNewParam param,
                                   @AuthenticationPrincipal CurrentPrincipal currentPrincipal) {
        Long[] productIdList = param.getProductIdList();
        Integer[] quantityList = param.getQuantityList();
        if (productIdList.length != quantityList.length) {
            throw new RequestParameterNotValidException("订单参数错误！");
        }
        orderService.addNew(param, currentPrincipal);
        return JsonResult.ok();
    }

    @Operation(summary = "[用户] 根据ID查询订单（限本人）")
    @ApiOperationSupport(order = 400)
    @Parameter(name = "id", description = "订单ID", required = true, example = "1")
    @GetMapping("/{id}")
    public JsonResult<OrderFullInfoVO> selectById(@PathVariable Long id, @AuthenticationPrincipal CurrentPrincipal currentPrincipal) {
        OrderFullInfoVO data = orderService.selectById(id, currentPrincipal);
        return JsonResult.ok(data);
    }

    @Operation(summary = "[用户] 查询订单列表（仅本人）")
    @ApiOperationSupport(order = 410)
    @Parameter(name = "page", description = "页码", example = "1", required = false)
    @GetMapping()
    public JsonResult<PageData<OrderSimpleInfoVO>> listByUser(Integer page, @AuthenticationPrincipal CurrentPrincipal currentPrincipal) {
        if (page == null || page < 1) {
            page = 1;
        }
        PageData<OrderSimpleInfoVO> data = orderService.listByUser(page, currentPrincipal);
        return JsonResult.ok(data);
    }

}